package dateTime

import (
	"fmt"
	"strings"
	"time"
)

const (
	TimeFormart  = "2006-01-02 15:04:05"
	TimeFormart2 = "2006-01-02 15:04:05.999"
)

type DateTime time.Time

func (t DateTime) MarshalJSON() ([]byte, error) {
	var stamp = fmt.Sprintf("\"%s\"", time.Time(t).Format("2006-01-02 15:04:05"))
	return []byte(stamp), nil
}

func (t DateTime) Format(format string) string {
	t2 := time.Time(t)
	return t2.Format(format)
}

func (t DateTime) Unix() int64 {
	t2 := time.Time(t)
	unix := t2.Unix()
	return unix
}

func (t DateTime) Before(u DateTime) bool {
	return t.ToTime().Before(u.ToTime())
}

func (t DateTime) After(u DateTime) bool {
	return t.ToTime().After(u.ToTime())
}

func (t DateTime) Equal(u DateTime) bool {
	dt1 := t.ToTime()
	dt2 := u.ToTime()
	return dt1.Equal(dt2)
}

// EqualMinTime 等于 1900-01-01 00:00:00
func (t DateTime) EqualMinTime() bool {
	dt, _ := time.Parse(TimeFormart, "1900-01-01 00:00:00")
	var isMinTime = t.ToTime().Equal(dt)
	return isMinTime
}

// EqualOrBeforeMinTime 小于或者等于 1900-01-01 00:00:00
func (t DateTime) EqualOrBeforeMinTime() bool {
	dt, _ := time.Parse(TimeFormart, "1900-01-01 00:00:00")
	var isMinTime = t.ToTime().Before(dt) || t.ToTime().Equal(dt)
	return isMinTime
}

func (t DateTime) ToTime() time.Time {
	return time.Time(t)
}

var LOC, _ = time.LoadLocation("Asia/Shanghai")

func (t *DateTime) UnmarshalJSON(data []byte) (err error) {
	defer func() {
		if r := recover(); r != nil {

		}
	}()

	value := string(data)
	value = strings.Replace(value, "T", " ", -1)
	value = strings.Replace(value, "\"", "", -1)
	if value == "" {
		return nil
	}
	if value == "string" {
		return nil
	}
	//len := len(value)
	//if len < 19 {
	//	return nil
	//}
	//value = value[0:19]
	//parse := carbon.Parse(value)
	//logHelper.Info(parse)
	var layouts = []string{"2006-01-02 15:04:05", "2006-1-2 15:04:05", "2006/1/2 15:04:05", "2006-01-02 15:04:05.999999999Z07:00"}
	timeVal := time.Time{}
	for _, layout := range layouts {
		timeVal, err = time.ParseInLocation(layout, value, time.Local)
		if err == nil {
			break
		}
	}
	*t = DateTime(timeVal)
	return nil
}

func (t DateTime) Now() DateTime {
	return DateTime(time.Now())
}

func Now() DateTime {
	return DateTime(time.Now())
}

func ToDateTime(t time.Time) DateTime {
	return DateTime(t)
}

func ToTime(t DateTime) time.Time {
	return time.Time(t)
}
